# coding=utf-8

import sys

import pexpect
from pexpect import *

from app.modules.common.pipelines import *
from app.modules.common.tasks import *
from app.modules.common.tasks import TaskExcecuteError, TaskParamsError
from app.modules.common.utils import *

log = logging.getLogger(__name__)


class BaseTask(Task):

    @abstractmethod
    def __do_execute__(self, params={}):
        pass

    def param_exists(self, key, params):
        keys = params.keys()
        if (key not in keys) or (params[key] is None) or ((str(params[key]).lstrip()) == ''):
            return False
        else:
            return True

    def create_path(self, path):

        log_proxy = self.get_log(log)
        log_proxy.info('********************************************************')
        log_proxy.info("=======> start create path [%s]", path)

        sh = '/bin/bash -c "mkdir -p %s"' % path

        log_proxy.info('=======> start execute shell : %s', sh)
        try:
            output, status = run(sh, withexitstatus=1, logfile=log_proxy)
            log_proxy.info('=======> shell status: %s, output: %s', status, output)
        except BaseException, e:
            log_proxy.info('=======> ' + e.message)
            raise TaskExcecuteError('execute shell failure, cause: %s.' % e.message)
        log_proxy.info('=======> end execute shell')

        if (status == 0) or (not status):
            log_proxy.info('=======> create path success.')
        else:
            log_proxy.info('=======> create path failure.')
            raise TaskExcecuteError('create path[%s] failure' % path)

    def remove_files(self, files_path):

        log_proxy = self.get_log(log)
        log_proxy.info('********************************************************')
        log_proxy.info("=======> start remove files [%s]", files_path)
        log_proxy.info('********************************************************')
        sh = '/bin/bash -c "rm -f %s"' % files_path

        log_proxy.info('=======> start execute shell : %s', sh)
        try:
            output, status = run(sh, withexitstatus=1, logfile=log_proxy)
            log_proxy.info('=======> shell status: %s, output: %s', status, output)
        except BaseException, e:
            log_proxy.error('=======> ' + e.message)
            raise TaskExcecuteError('execute shell failure, cause: %s.' % e.message)

        if (status == 0) or (not status):
            log_proxy.info('=======> clean files_path[%s] success.', files_path)
        else:
            raise TaskExcecuteError('clean files_path[%s] failure.', files_path)
